package com.jied.duodian.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@EnableCaching // 开启缓存
@Configuration
// @AutoConfigureAfter(RedisAutoConfiguration.class)
@Slf4j
public class RedisConfig {


    //配置Redistemplate
    @Bean("redisTemplate")
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory( redisConnectionFactory );
        template.setValueSerializer( keySerializer() );
        template.setHashValueSerializer( keySerializer() );
        template.setKeySerializer( valueSerializer() );
        template.setHashKeySerializer( valueSerializer() );
        template.afterPropertiesSet();
        log.debug( "自定义RedisTemplate加载完成" );
        return template;
    }

    private RedisSerializer<String> keySerializer() {
        return new StringRedisSerializer();
    }

    private RedisSerializer<Object> valueSerializer() {
        return new GenericJackson2JsonRedisSerializer();
    }


    /**
     * 缓存管理器配置
     *
     * @param redisConnectionFactory
     * @return
     */
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        // 生成一个默认配置，通过config对象即可对缓存进行自定义配置
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        // 设置缓存的默认过期时间，也是使用Duration设置
        config = config.entryTtl( Duration.ofMinutes( 10 ) )
                // 设置 key为string序列化
                .serializeKeysWith( RedisSerializationContext.SerializationPair.fromSerializer( keySerializer() ) )
                // 设置value为json序列化
                .serializeValuesWith( RedisSerializationContext.SerializationPair.fromSerializer( valueSerializer() ) )
                // 不缓存空值
                .disableCachingNullValues();

        // 对每个缓存空间应用不同的配置
        Map<String, RedisCacheConfiguration> configMap = new HashMap<>();
        configMap.put( "qt", config );
        configMap.put( "user", config.entryTtl( Duration.ofSeconds( 120 ) ) );

        // 使用自定义的缓存配置初始化一个cacheManager
        RedisCacheManager cacheManager = RedisCacheManager.builder( redisConnectionFactory )
                .cacheDefaults( config )
                .transactionAware()
                .withInitialCacheConfigurations( configMap )
                .build();
        log.debug( "自定义RedisCacheManager加载完成" );
        return cacheManager;
    }

    /**
     * 缓存的key是 包名+方法名+参数列表
     */
    @Bean
    public KeyGenerator keyGenerator() {
        return (target, method, objects) -> {
            StringBuilder sb = new StringBuilder();
            sb.append( target.getClass().getName() );
            sb.append( "::" + method.getName() + ":" );
            for (Object obj : objects) {
                sb.append( obj.toString() );
            }
            return sb.toString();
        };
    }

}
